import express from "express";
import fs from "fs";
import { loadEnv as _loadEnv, createServer } from "vite";
import { resolve, join, dirname } from "path";
import { fileURLToPath } from "url";

const root = join(dirname(fileURLToPath(import.meta.url)), "..");

const loadEnv = () => {
  const i = process.argv.findIndex((it) => it === "--mode" || it === "-m");
  const mode = i < 0 ? "development" : process.argv[i + 1] || "development";
  return _loadEnv(mode, root);
};

const env = loadEnv();

const server = express();

console.log({ env,root });

const viteServer = await createServer({
  appType: "custom",
  root,
  server: {
    middlewareMode: true,
    proxy: {
      "/api": {
        target: env.VITE_API_BASE_URL,
        changeOrigin: true,
        ws: true,
        rewrite: (v) => {
          console.log("proxy", v);
          return v.replace(/^\/api/, "");
        },
      },
    },
  },
});

server.use(viteServer.middlewares);

server.use("*", async (req, res, next) => {
  try {
    const url = req.originalUrl;

    // always read fresh template in dev
    let template = fs.readFileSync(resolve("index.html"), "utf-8");
    template = await viteServer.transformIndexHtml(url, template);
    const render = (await viteServer.ssrLoadModule("./src/entry-server.ts"))
      .render;

    const ctx = {};

    const html = await render(url, {}, ctx, template);
    res.set({ "Content-Type": "text/html" }).end(html);
  } catch (e) {
    viteServer.ssrFixStacktrace(e);
    next(e);
  }
});

server.listen(9010, () => {
  console.log("look at http://localhost:9010");
});
